/**
 * Created by huachuan on 2016/1/11.
 */
angular.module('mecollectcontrollers', [])
  //我的收藏的Controller
  .controller('MeCollectCtrl', function($scope,$rootScope,$ionicSlideBoxDelegate,$cordovaStatusbar,$cordovaFileTransfer,$ionicPopup,$state,$timeout,$ionicScrollDelegate,$ionicActionSheet,ENV,MeCollect,Home,Wine,Meeting,Toast,Storage,History,Loading,Magazine,News,ShareServiceOther,ShareService) {
    //获取会员编号
    var memberId = '';
    $scope.picPath = ENV.picPath;
    $scope.isShareShow = ShareService.getIsShowShareWindow();//判断是否显示分享框
    //显示那一个
    $scope.showWhich = [true,false,false,false,false,false,false];
    //是否点击了编辑按钮
    $scope.showEdit = false;
    $scope.rightBtnText = '编辑';
    $scope.clickEditBtn = function(){
      if($scope.rightBtnText=='编辑'){
        $scope.showEdit = true;
        $scope.rightBtnText = '取消';
      }else if($scope.rightBtnText=='取消'){
        $scope.showEdit = false;
        $scope.rightBtnText = '编辑';
      }
    };
    //保存的数据
    $scope.collectWineList = [];
    $scope.collectMeetingList = [];
    $scope.collectHomeList = [];
    $scope.collectMessageList = [];
    $scope.collectVideoList =[];
    $scope.collectBookList = [];
    $scope.collectChapterList = [];
    //是否显示底部取消收藏的提示框
    $scope.showConfirmNoCollect = false;

    /*******************************************/
    $scope.slideChanged = function(prePage){
      $scope.showWhich = [false,false,false,false];
      $scope.showWhich[prePage] = true;
      if(prePage==0){
        showCollectWineFun();
        MeCollect.getWineList(memberId);
      }else if(prePage==1){
        showCollectMeetingFun();
        MeCollect.getMeMeetingList(memberId);
      }else if(prePage==2){
        showCollectHomeFun();
        MeCollect.getHomeList(memberId);
      }else if(prePage==3){
        showCollectMessageFun();
        MeCollect.getMessageList(memberId);
      }else if(prePage==4){
        showCollectVideoFun();
        MeCollect.getVideoList(memberId);
      }else if(prePage==5){
        showCollectBookFun();
        MeCollect.getBookList(memberId);
      }else if(prePage==6){
        showCollectChapterFun();
        MeCollect.getChapterList(memberId);
      }
    }
    //刚刚进入页面的时候进行局部刷新
    $scope.$on('$ionicView.beforeEnter', function () {
      memberId = Storage.get("member").member_id;
      if($scope.showWhich[0]){
        MeCollect.getWineList(memberId);
      }else if($scope.showWhich[1]){
        MeCollect.getMeMeetingList(memberId);
      }else if($scope.showWhich[2]){
        MeCollect.getHomeList(memberId);
      }else if($scope.showWhich[3]){
        MeCollect.getMessageList(memberId);
      }else if($scope.showWhich[4]){
        MeCollect.getVideoList(memberId);
      }else if($scope.showWhich[5]){
        MeCollect.getBookList(memberId);
      }else if($scope.showWhich[6]){
        MeCollect.getChapterList(memberId);
      }
    });
    //收藏或者取消收藏Meeting
    $scope.collectMeeting = function(index,mmId){
      Meeting.collectMeeting(memberId,mmId);
      likeOrCollectIndex = index;
    };
    //网络访问成功后
    $scope.$on('Meeting.collectMeetingUpdated', function(){
      var result = Meeting.getCollectJson();
      Toast.showMessage(result.mcmeetMsg);
      $scope.collectMeetingList.splice(likeOrCollectIndex,1);
      likeOrCollectIndex = '';
    });
    //点赞Meeting
    var likeOrCollectIndex = '';
    $scope.likeMeeting = function(index,mmId){
      likeOrCollectIndex = index;
      Meeting.likeMeeting(memberId,mmId);
    };
    //网络访问成功后
    $scope.$on('Meeting.likeMeetingUpdated', function(){
      var result = Meeting.getLikeJson();
      $scope.collectMeetingList[likeOrCollectIndex].lmeetStatus = result.lmeetStatus;
      Toast.showMessage(result.lmeetMsg);
      likeOrCollectIndex='';
    });
    //收藏酒窝
    var collectorLikeHomeIndex = '';
    $scope.collectHome =function(index,mhId){
      Home.collectHome(memberId,mhId);
      collectorLikeHomeIndex = index;
    };
    $scope.$on('Home.collectHomeUpdated',function(){
      var result = Home.getCollectHomeMsgJson();
      Toast.showMessage(result.mchomeMsg);
      $scope.collectHomeList.splice(collectorLikeHomeIndex,1);
    });
    //点赞酒窝
    $scope.likeHome =function(index,mhId){
      Home.likeHome(memberId,mhId);
      collectorLikeHomeIndex = index;
    };
    $scope.$on('Home.likeHomeUpdated',function(){
      var result = Home.getLikeHomeMsgJson();
      Toast.showMessage(result.lhomeMsg);
      $scope.collectHomeList[collectorLikeHomeIndex].lhomeStatus = result.lhomeStatus;
    });
    //确定取消收藏
    $scope.cancelCollect = function(){
      //$scope.showConfirmNoCollect = false;
      if($scope.showWhich[0]){
          var noCollectWineIds = [];
          for(i=0;i<$scope.collectWineList.length;i++){
              if($scope.collectWineList[i].selected){
                noCollectWineIds.push($scope.collectWineList[i].mc_id);
              }
          }
        if(noCollectWineIds.length==0){
          Toast.showMessage("请选择要取消收藏的酒款");
        }else{
          $ionicPopup.confirm({
            template: '<p style="text-align: center;font-size:16px;">确定要取消收藏吗？</p>',
            cancelText: '取消',
            okText: '确定',
            okType: 'hd-red-btn',
            cancelType: 'cancel-esc-btn'
          }).then(function (res) {
            if (res) {
              Loading.showLoading();
              MeCollect.no2Collect(noCollectWineIds);
            }
          });

        }
      }else if($scope.showWhich[3]){
          var noCollectMessageIds = [];
          for(i=0;i<$scope.collectMessageList.length;i++){
            if($scope.collectMessageList[i].selected){
              noCollectMessageIds.push($scope.collectMessageList[i].mc_id);
            }
          }
        if(noCollectMessageIds.length==0){
          Toast.showMessage("请选择要取消收藏的资讯");
        }else{
          $ionicPopup.confirm({
            template: '<p style="text-align: center;font-size:16px;">确定要取消收藏吗？</p>',
            cancelText: '取消',
            okText: '确定',
            okType: 'hd-red-btn',
            cancelType: 'cancel-esc-btn'
          }).then(function (res) {
            if (res) {
              Loading.showLoading();
              MeCollect.no2Collect(noCollectMessageIds);
            }
          });
        }
      }else if($scope.showWhich[4]){
          var noCollectVideoIds = [];
        for(i=0;i<$scope.collectVideoList.length;i++){
          if($scope.collectVideoList[i].selected){
            noCollectVideoIds.push($scope.collectVideoList[i].mc_id);
          }
        }
        if(noCollectVideoIds.length==0){
          Toast.showMessage("请选择要取消收藏的视频");
        }else{
          $ionicPopup.confirm({
            template: '<p style="text-align: center;font-size:16px">确定要取消收藏吗？</p>',
            cancelText: '取消',
            okText: '确定',
            okType: 'hd-red-btn',
            cancelType: 'cancel-esc-btn'
          }).then(function (res) {
            if (res) {
              Loading.showLoading();
              MeCollect.no2Collect(noCollectVideoIds);
            }
          });
        }
      }else if($scope.showWhich[5]){
        var noCollectBookIds = [];
        for(i=0;i<$scope.collectBookList.length;i++){
          if($scope.collectBookList[i].selected){
            noCollectBookIds.push($scope.collectBookList[i].mc_id);
          }
        }
        if(noCollectBookIds.length==0){
          Toast.showMessage("请选择要取消收藏的书籍");
        }else{
          $ionicPopup.confirm({
            template: '<p style="text-align: center;font-size:16px">确定要取消收藏吗？</p>',
            cancelText: '取消',
            okText: '确定',
            okType: 'hd-red-btn',
            cancelType: 'cancel-esc-btn'
          }).then(function (res) {
            if (res) {
              Loading.showLoading();
              MeCollect.no2Collect(noCollectBookIds);
            }
          });
        }
      }else if($scope.showWhich[6]){
        var noCollectChapterIds = [];
        for(i=0;i<$scope.collectChapterList.length;i++){
          if($scope.collectChapterList[i].selected){
            noCollectChapterIds.push($scope.collectChapterList[i].mc_id);
          }
        }
        if(noCollectChapterIds.length==0){
          Toast.showMessage("请选择要取消收藏的章节");
        }else{
          $ionicPopup.confirm({
            template: '<p style="text-align: center;font-size:16px">确定要取消收藏吗？</p>',
            cancelText: '取消',
            okText: '确定',
            okType: 'hd-red-btn',
            cancelType: 'cancel-esc-btn'
          }).then(function (res) {
            if (res) {
              Loading.showLoading();
              MeCollect.no2Collect(noCollectChapterIds);
            }
          });
        }
      }
    };
    //访问网络成功后的回调方法
    $scope.$on('MeCollect.noCollectWineUpdated',function(){
      Loading.hideLoading();
      var result = MeCollect.getNo2CollectJson();
      if($scope.showWhich[0]){
          MeCollect.getWineList(memberId);
      }else if($scope.showWhich[1]){
          MeCollect.getMeMeetingList(memberId);
      }else if($scope.showWhich[2]){
          MeCollect.getHomeList(memberId);
      }else if($scope.showWhich[3]){
          MeCollect.getMessageList(memberId);
      }else if($scope.showWhich[4]){
          MeCollect.getVideoList(memberId);
      }else if($scope.showWhich[5]){
          MeCollect.getBookList(memberId);
      }else if($scope.showWhich[6]){
          MeCollect.getChapterList(memberId);
      }
      Toast.showMessage(result.deleteCollectMsg);
    });
    //切换Tab的时候
    function changeTab(){
      $ionicScrollDelegate.scrollTop();
      $scope.showEdit = false;
      $scope.rightBtnText = '编辑';
      $scope.bottomCheckBoxSelected = false;
      for(i=0;i<$scope.collectWineList.length;i++){
        $scope.collectWineList[i].selected = false;
      }
      for(i=0;i<$scope.collectMeetingList.length;i++){
        $scope.collectMeetingList[i].selected = false;
      }
      for(i=0;i<$scope.collectMessageList.length;i++){
        $scope.collectMessageList[i].selected = false;
      }
      for(i=0;i<$scope.collectVideoList.length;i++){
        $scope.collectVideoList[i].selected = false;
      }
      for(i=0;i<$scope.collectBookList.length;i++){
        $scope.collectBookList[i].selected = false;
      }
      for(i=0;i<$scope.collectChapterList.length;i++){
        $scope.collectChapterList[i].selected = false;
      }
    }
    //全选全部酒款,资讯，书籍，视频，章节
    $scope.selectAllBottom = function(){
        if($scope.bottomCheckBoxSelected){
          if($scope.showWhich[0]){
            for(i=0;i<$scope.collectWineList.length;i++){
              $scope.collectWineList[i].selected = false;
            }
          }else if($scope.showWhich[3]){
            for(i=0;i<$scope.collectMessageList.length;i++){
              $scope.collectMessageList[i].selected = false;
            }
          }else if($scope.showWhich[4]){
            for(i=0;i<$scope.collectVideoList.length;i++){
              $scope.collectVideoList[i].selected = false;
            }
          }else if($scope.showWhich[5]){
            for(i=0;i<$scope.collectBookList.length;i++){
              $scope.collectBookList[i].selected = false;
            }
          }else if($scope.showWhich[6]){
            for(i=0;i<$scope.collectChapterList.length;i++){
              $scope.collectChapterList[i].selected = false;
            }
          }
        }else{
          if($scope.showWhich[0]){
            for(i=0;i<$scope.collectWineList.length;i++){
              $scope.collectWineList[i].selected = true;
            }
          }else if($scope.showWhich[3]){
            for(i=0;i<$scope.collectMessageList.length;i++){
              $scope.collectMessageList[i].selected = true;
            }
          }else if($scope.showWhich[4]){
            for(i=0;i<$scope.collectVideoList.length;i++){
              $scope.collectVideoList[i].selected = true;
            }
          }else if($scope.showWhich[5]){
            for(i=0;i<$scope.collectBookList.length;i++){
              $scope.collectBookList[i].selected = true;
            }
          }else if($scope.showWhich[6]){
            for(i=0;i<$scope.collectChapterList.length;i++){
              $scope.collectChapterList[i].selected = true;
            }
          }
        }
        $scope.bottomCheckBoxSelected = !$scope.bottomCheckBoxSelected;
    };
    /**************显示收藏的酒款*******************/
    //下拉刷新
   /* $scope.doRefresh = function(){
      if($scope.showWhich[0]){
        MeCollect.getWineList(memberId);
      }else if($scope.showWhich[1]){
        MeCollect.getMeMeetingList(memberId);
      }else if($scope.showWhich[2]){
        MeCollect.getHomeList(memberId);
      }else if($scope.showWhich[3]){
        MeCollect.getMessageList(memberId);
      }else if($scope.showWhich[4]){
        MeCollect.getVideoList(memberId);
      }else if($scope.showWhich[5]){
        MeCollect.getBookList(memberId);
      }else if($scope.showWhich[6]){
        MeCollect.getChapterList(memberId);
      }
    };*/
    $scope.doRefreshWine = function(){MeCollect.getWineList(memberId);}
    $scope.doRefreshMeeting = function(){MeCollect.getMeMeetingList(memberId);}
    $scope.doRefreshHome = function(){MeCollect.getHomeList(memberId);}
    $scope.doRefreshMessage = function(){MeCollect.getMessageList(memberId);}
    $scope.doRefreshVideo = function(){MeCollect.getVideoList(memberId);}
    $scope.doRefreshBook = function(){MeCollect.getBookList(memberId);}
    $scope.doRefreshChapter = function(){MeCollect.getChapterList(memberId);}

    //底部的全选复选框样式
    $scope.bottomCheckBoxSelected = false;
    $scope.showCollectWine = function(){
      $ionicSlideBoxDelegate.slide(0,300);
      showCollectWineFun();
    };
    showCollectWineFun = function(){
      $scope.showWhich = [true,false,false,false,false,false,false];
      changeTab();
    }
    Loading.showLoading();
    MeCollect.getWineList(memberId);
    $scope.$on('MeCollect.WineCollectListUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.collectWineList = MeCollect.getWineListJson().collectWineList;
    });
    $scope.selectCollectWine=function(index){
      if($scope.collectWineList[index].selected){
        $scope.bottomCheckBoxSelected = false;
      }
      $scope.collectWineList[index].selected = !$scope.collectWineList[index].selected;
    };
    //加入推荐酒单
    $scope.addToWineRecommend = function(){
      var recommendInfo = [];
      for(i=0;i<$scope.collectWineList.length;i++){
        if($scope.collectWineList[i].selected){
          temp ={
            wine_id:$scope.collectWineList[i].wine_id,
            member_id:memberId
          };
          recommendInfo.push(temp);
        }
      }
      //加入推荐酒单
      if(recommendInfo!=null && recommendInfo.length!=0){
        Wine.add2WineRecommend(recommendInfo);
      }else{
        Toast.showMessage("请选择酒款");
      }
    };
    $scope.$on('Wine.add2WineRecommendUpdated',function(){
      var result = Wine.getAddWineRecommendJson();
      Toast.showMessage(result.insertWineMsg);
    });
    /**************显示收藏的酒款结束*******************/


    /******************显示收藏的活动******************/
    var firstInCollectMeeting = true;
    $scope.showCollectMeeting = function(){
      $ionicSlideBoxDelegate.slide(1,300);
      showCollectMeetingFun();
    };
    showCollectMeetingFun = function(){
      $scope.showWhich = [false,true,false,false,false,false,false];
      changeTab();
      if(firstInCollectMeeting){
        Loading.showLoading();
        firstInCollectMeeting = false;
      }
    }
    $scope.$on('MeCollect.MeetingCollectListUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.collectMeetingList = MeCollect.getMeMeetingListJson().collectMeetingList;
    });
    /******************显示收藏的活动结束******************/
    /*********************显示收藏的酒窝*****************/
    var firstInCollectHome = true;
    $scope.showCollectHome = function(){
      $ionicSlideBoxDelegate.slide(2,300);
      showCollectHomeFun();
    };
    showCollectHomeFun = function(){
      $scope.showWhich = [false,false,true,false,false,false,false];
      changeTab();
      if(firstInCollectHome){
        Loading.showLoading();
        firstInCollectHome = false;
      }
    }
    $scope.$on('MeCollect.HomeCollectListUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.collectHomeList = MeCollect.getHomeListJson().collectHomeList;
    });
    //酒窝显示大图

    $scope.showBigImage= function(homeIndex,picIndex){
      var items = [];
      var lookImageList = $scope.collectHomeList[homeIndex].picSrc;
      var pswpElement = document.querySelectorAll('.pswp')[0];
      for(i=0;i<lookImageList.length;i++){
        var temp = {
          src:$scope.picPath+"big_"+lookImageList[i].src,
          w:lookImageList[i].w,
          h:lookImageList[i].h
        };
        items.push(temp);
      }
      var options = {
        index: picIndex,
        history: false,
        focus: false,
        loop: false,
       /* pinchToClose:false,
        closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true,
        loadingIndicatorDelay:100
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
     // $cordovaStatusbar.hide();
    };
    $rootScope.downloadHomeImg = function(){
      var url = $rootScope.gallery.currItem.src;
      var timestamp=new Date().getTime();
      var targetPath= cordova.file.externalRootDirectory+"winelife/winelife_home_"+timestamp+".jpg";
      var trustHosts = true;
      var options = {};
      $ionicActionSheet.show({
       buttons: [
       {text: '保存到手机相册'}
       ],
       cancelText: '取消',
       buttonClicked: function (index) {
       if(index==0){
       $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
       .then(function(result) {
          Toast.showMessage("保存成功");
       }, function(err) {
           Toast.showMessage("保存成功");
       }, function (progress) {
       });
       }
       return true;
       }
       });
    }
    //单击缩小图片
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
    // $cordovaStatusbar.show();
    };

    /*********************显示收藏的酒窝结束*****************/
    /***********显示收藏的资讯**************/
    $scope.readMessage = function(messageId,fromWhere){
      News.saveFromWhere(fromWhere);
      $state.go('newsDetails',{'messageId':messageId});
    }
   var firstInCollectInMessage = true;
    $scope.showCollectMessage = function(){
      $ionicSlideBoxDelegate.slide(3,300);
      showCollectMessageFun();
    };
    showCollectMessageFun = function(){
      $scope.showWhich = [false,false,false,true,false,false,false];
      changeTab();
      if(firstInCollectInMessage){
        Loading.showLoading();
        firstInCollectInMessage = false;
      }
    }
    $scope.$on('MeCollect.MessageCollectListUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.collectMessageList = MeCollect.getMessageListJson().collectMessageList;
    });
    $scope.selectCollectMessage = function(index){
      if($scope.collectMessageList[index].selected){
        $scope.bottomCheckBoxSelected = false;
      }
      $scope.collectMessageList[index].selected = !$scope.collectMessageList[index].selected;
    };
    /***********显示收藏的资讯结束**************/
    /************显示收藏的视频****************/
    var firstInCollectVideo = true;
    $scope.showCollectVideo = function(){
      $ionicSlideBoxDelegate.slide(4,300);
      showCollectVideoFun();
    };
    showCollectVideoFun = function(){
      $scope.showWhich = [false,false,false,false,true,false,false];
      changeTab();
      if(firstInCollectVideo){
        Loading.showLoading();
        firstInCollectVideo = false;
      }
    }
    $scope.$on('MeCollect.VideoCollectListUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.collectVideoList = MeCollect.getVideoListJson().collectVideoList;
    });
    $scope.selectCollectVideo = function(index){
      if($scope.collectVideoList[index].selected){
        $scope.bottomCheckBoxSelected = false;
      }
      $scope.collectVideoList[index].selected = !$scope.collectVideoList[index].selected;
    };
    /************显示收藏的视频结束****************/
    /**************显示收藏的书籍******************/
   var firstInCollectBook = true;
    $scope.showCollectBook = function(){
      $ionicSlideBoxDelegate.slide(5,300);
      showCollectBookFun();
    };
    showCollectBookFun = function(){
      $scope.showWhich = [false,false,false,false,false,true,false];
      changeTab();
      if(firstInCollectBook){
        Loading.showLoading();
        firstInCollectBook = false;
      }
    }
    $scope.$on('MeCollect.BookCollectListUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.collectBookList = MeCollect.getBookListJson().collectBookList;
    });
    $scope.selectCollectBook = function(index){
      if($scope.collectBookList[index].selected){
        $scope.bottomCheckBoxSelected = false;
      }
      $scope.collectBookList[index].selected = !$scope.collectBookList[index].selected;
    };
    //读取的书籍
    $scope.readBook = function(bookId,fromWhere){
      Magazine.saveFromWhere(fromWhere);
      $state.go("book-catalog",{'magazineId':bookId});

    }
    /**************显示收藏的章节*************/
      $scope.readBookDetail = function(bdId,fromWhere){
        $state.go('book-details',{'bdId':bdId});
        Magazine.saveBdFromWhere(fromWhere);
      }
    var firstInCollectChapter = true;
    $scope.showCollectChapter = function(){
      $ionicSlideBoxDelegate.slide(6,300);
      showCollectChapterFun();
    };
    showCollectChapterFun = function(){
      $scope.showWhich = [false,false,false,false,false,false,true];
      changeTab();
      if(firstInCollectChapter){
        Loading.showLoading();
        firstInCollectChapter = false;
      }
    }
    $scope.$on('MeCollect.ChapterCollectListUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.collectChapterList = MeCollect.getChapterListJson().collectChapterList;
    });
    $scope.selectCollectChapter = function(index){
      if($scope.collectChapterList[index].selected){
        $scope.bottomCheckBoxSelected = false;
      }
      $scope.collectChapterList[index].selected = !$scope.collectChapterList[index].selected;
    };
    /**************显示收藏的章节结束*************/
    //返回
    $scope.goback = function(){History.goback()};


    //显示约局分享框
    $scope.showMeetingShare = function(mm_id){
      ShareServiceOther.showShareWindow(mm_id,"meeting");
    };

    //显示酒窝分享框
    $scope.showHomeShare = function(mh_id){
      ShareServiceOther.showShareWindow(mh_id,"home");
    };

    //改变数字的显示，添加逗号分割
    $scope.getFormatNum = function (num) {
      return formatNum(num);
    };


  });
